package com.qbccn.usercenter.config;

import com.alibaba.fastjson.JSONObject;
import com.qbccn.usercenter.mapper.UcUserMapper;
import com.qbccn.usercenter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linke
 * @date 2020/5/23 18:24
 * @description 用户登录成功时返回给前端的数据
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UcUserMapper ucUserMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("message", "登录成功！");
        httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
        httpServletResponse.getWriter().write(jsonObject.toJSONString());
        User user = (User) authentication.getPrincipal();
        httpServletRequest.getSession().setAttribute("userInfo", ucUserMapper.getUserInfo(user.getUsername()));
    }
}
